﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Wei_DB;
using Wei_Model;

namespace BLL
{
    public class UsersBLL
    {





        public Wei_UsersModel Login(string email, string pwd)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(pwd));
            pwd = System.Text.Encoding.Default.GetString(result);

            //System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "MD5");

            using (WeiDB db = new WeiDB())
            {
                var sql = (from a in db.Wei_Users
                           where a.Email == email && a.Password == pwd
                           select new Wei_UsersModel()
                           {
                               Email = a.Email,
                               Id = a.Id,
                               Active = a.Active,
                               Is_OnLine = a.Is_OnLine,
                               Role = a.Role,
                               User_Name = a.User_Name,
                               Last_Login_Time = a.Last_Login_Time
                           }).FirstOrDefault();
                return sql;
            }
        }


        public string Register(Wei_UsersModel user)
        {
            using (WeiDB db = new WeiDB())
            {
                var sql = db.Wei_Users.Where(u=> u.Email == user.Email && u.User_Name == user.User_Name).FirstOrDefault();
                if (sql == null)
                {
                
                    MD5 md5 = new MD5CryptoServiceProvider();
                    byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(user.Password));
                    user.Password = System.Text.Encoding.Default.GetString(result);
                    Wei_Users users = new Wei_Users()
                    {
                        Email = user.Email,
                        User_Name = user.User_Name,
                        Password = user.Password,
                        Is_OnLine = 0,
                        Active = 1,
                        Create_Time = DateTime.Now,
                        Role = 1,
                        Last_Login_Time = DateTime.Now,
                        Last_Update_Password_Time = DateTime.Now,
                    };
                    db.Wei_Users.Add(users);
                    db.SaveChanges();
                    return "成功";
                }
                else
                {
                    if (sql.User_Name == user.User_Name)
                    {
                        return "昵称已存在";
                    }
                    if(sql.Email == user.Email)
                    {
                        return "Email已存在";
                    }
                }
            }
            return "失败";
        }








    }
}
